import areaInsertOrUpdateApi from '@/api/area/areaInsertOrUpdateApi'
import areaTreeApi from '@/api/area/areaTreeApi'
import doDelDataClick from '@/api/common/delDataApi'
import notBlankIdApi from '@/api/common/notBlankIdApi'
import CAddOrderNo, { checkIdSet } from '@/components/CAddOrderNo/CAddOrderNo'
import CSearchForm from '@/components/CSearchForm/CSearchForm'
import IAreaInsertOrUpdateForm from '@/model/form/area/IAreaInsertOrUpdateForm'
import IAreaPageForm from '@/model/form/area/IAreaPageForm'
import IAreaVO from '@/model/vo/area/IAreaVO'
import { calcOrderNo, onModalCancel, ToastSuccess } from '@/util/CommonUtil'
import { IconChevronDown, IconRefresh, IconSearch } from '@douyinfe/semi-icons'
import {
  Badge,
  Button,
  ButtonGroup,
  Dropdown,
  Form,
  Modal,
  Row,
  Space,
} from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import {
  Dispatch,
  MutableRefObject,
  SetStateAction,
  useEffect,
  useRef,
  useState,
} from 'react'
import CTable from '../../../components/CTable/CTable'
import AreaColumns from './AreaColumns'
import AreaFormItem, { getAreaFormSelectData } from './AreaFormItem'
import AreaSearchFormItem from './AreaSearchFormItem'

export default function Area() {
  const [selectedRowKeyList, setSelectedRowKeyList] = useState<
    (string | number)[]
  >([]) // 表格选中的 key集合
  const [loading, setLoading] = useState(false)
  const [expandAllRowsFlag, setExpandAllRowsFlag] = useState(true) // 是否展开所有行
  const [dataSource, setDataSource] = useState<IAreaVO[]>([])
  const [modalTitle, setModalTitle] = useState('')
  const [modalVisible, setModalVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态
  const [initForm, setInitForm] = useState<IAreaInsertOrUpdateForm>({}) // modal表单初始值
  const [addOrderNoVisible, setAddOrderNoVisible] = useState(false) // 加减排序号 modal是否显示
  const [sideSheetVisible, setSideSheetVisible] = useState(false) // 搜索 sideSheet是否显示
  const [searchForm, setSearchForm] = useState<IAreaPageForm>({}) // 搜索表单初始值

  const formApi = useRef<FormApi>()

  // 执行获取 table数据
  function doGetTableData() {
    getTableData(setDataSource, setLoading, searchForm)
  }

  useEffect(() => {
    doGetTableData()
  }, [])

  const { deptList } = getAreaFormSelectData(modalVisible)

  return (
    <div className="p-l-r-20">
      <CSearchForm
        sideSheetVisible={sideSheetVisible}
        setSideSheetVisible={setSideSheetVisible}
        getTableData={(values: any) => {
          getTableData(setDataSource, setLoading, values)
        }}
        setSearchForm={setSearchForm}
      >
        <AreaSearchFormItem></AreaSearchFormItem>
      </CSearchForm>

      <CAddOrderNo
        url={'/area/addOrderNo'}
        idSet={selectedRowKeyList}
        getTableData={doGetTableData}
        addOrderNoVisible={addOrderNoVisible}
        setAddOrderNoVisible={setAddOrderNoVisible}
      />

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={() => {
          formApi.current?.submitForm()
        }}
        onCancel={() => {
          onModalCancel(setModalVisible, formApi.current, initForm)
        }}
        maskClosable={false}
        confirmLoading={confirmLoading}
      >
        <Form
          onSubmit={(form) => {
            if (confirmLoading) return
            modalSubmitClick(
              form,
              setConfirmLoading,
              setModalVisible,
              doGetTableData
            )
          }}
          disabled={confirmLoading}
          getFormApi={(api) => (formApi.current = api)}
          initValues={initForm}
        >
          <Row gutter={30}>
            <AreaFormItem deptList={deptList} areaTree={dataSource} />
          </Row>
        </Form>
      </Modal>

      <div className="flex jc-sb m-t-b-10">
        <Space>
          <Button
            theme="solid"
            onClick={() => {
              const initFormTemp: IAreaInsertOrUpdateForm = {
                enableFlag: true,
              }
              calcOrderNo(initFormTemp, { children: dataSource })
              setInitForm(initFormTemp)
              setModalTitle('新增区域')
              setModalVisible(true)
            }}
          >
            新增
          </Button>
          <Button
            theme="solid"
            type="danger"
            onClick={() => {
              delData(selectedRowKeyList, setSelectedRowKeyList, doGetTableData)
            }}
          >
            删除
          </Button>
          <Dropdown
            clickToHide
            stopPropagation
            render={
              <Dropdown.Menu>
                <Dropdown.Item
                  onClick={() => {
                    if (!checkIdSet(selectedRowKeyList)) {
                      return
                    }
                    setAddOrderNoVisible(true)
                  }}
                >
                  加减排序号
                </Dropdown.Item>
                <Dropdown.Item
                  onClick={() => setExpandAllRowsFlag(!expandAllRowsFlag)}
                >
                  展开/收起
                </Dropdown.Item>
              </Dropdown.Menu>
            }
          >
            <Button
              type="tertiary"
              iconPosition="right"
              icon={<IconChevronDown />}
            >
              更多操作
            </Button>
          </Dropdown>
        </Space>

        {/* @ts-ignore */}
        <ButtonGroup>
          <Button
            onClick={() => {
              setSideSheetVisible(true)
            }}
            icon={
              <Badge dot={Object.keys(searchForm).length !== 0} type="warning">
                <IconSearch title="搜索" className="flex ai-c" />
              </Badge>
            }
          ></Button>
          <Button
            onClick={() => {
              if (!loading) {
                doGetTableData()
              }
            }}
            disabled={loading}
            icon={<IconRefresh spin={loading} title="刷新" />}
          ></Button>
        </ButtonGroup>
      </div>

      <CTable<IAreaVO>
        hiddenIndex
        columns={AreaColumns}
        pagination={{ pageSize: dataSource.length }}
        expandAllRows={expandAllRowsFlag}
        dataSource={dataSource}
        defaultOperateClickFun={(text, record, index) => {
          editData(
            setInitForm,
            setModalTitle,
            setModalVisible,
            setConfirmLoading,
            record,
            formApi,
            confirmLoading
          )
        }}
        operateDropdownItem={(text, record, index) => (
          <>
            <Dropdown.Item
              onClick={() => {
                editData(
                  setInitForm,
                  setModalTitle,
                  setModalVisible,
                  setConfirmLoading,
                  record,
                  formApi,
                  confirmLoading
                )
              }}
            >
              编辑
            </Dropdown.Item>
            <Dropdown.Item
              onClick={() => {
                const initFormTemp: IAreaInsertOrUpdateForm = {
                  enableFlag: true,
                  parentId: record.id,
                }
                calcOrderNo(initFormTemp, record)
                setInitForm(initFormTemp)
                setModalTitle('新增区域')
                setModalVisible(true)
              }}
            >
              添加下级
            </Dropdown.Item>
            <Dropdown.Item
              className="red"
              onClick={() => {
                delData(
                  selectedRowKeyList,
                  setSelectedRowKeyList,
                  doGetTableData,
                  record
                )
              }}
            >
              删除
            </Dropdown.Item>
          </>
        )}
        loading={loading}
        selectedRowKeyList={selectedRowKeyList}
        setSelectedRowKeyList={setSelectedRowKeyList}
      />
    </div>
  )
}

// 编辑数据
function editData(
  setInitForm: Dispatch<SetStateAction<IAreaInsertOrUpdateForm>>,
  setModalTitle: Dispatch<SetStateAction<string>>,
  setModalVisible: Dispatch<SetStateAction<boolean>>,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  record: IAreaVO,
  formApi: MutableRefObject<FormApi<any> | undefined>,
  confirmLoading: boolean
) {
  if (confirmLoading) {
    return
  }
  setInitForm({ id: record.id }) // 重置 initForm的值
  setModalTitle('编辑区域')
  setModalVisible(true)
  setConfirmLoading(true)
  notBlankIdApi<IAreaVO>('/area/infoById', { id: record.id }).then(
    ({ data }) => {
      setInitForm(data.data)
      formApi.current?.setValues(data.data, { isOverride: true })
      setConfirmLoading(false)
    }
  )
}

// 获取 table数据
function getTableData(
  setDataSource: Dispatch<SetStateAction<IAreaVO[]>>,
  setLoading: Dispatch<SetStateAction<boolean>>,
  searchForm: IAreaPageForm
) {
  setLoading(true)
  areaTreeApi({
    ...searchForm,
    defaultOrderFlag: true,
    orderList: [{ name: 'orderNo', value: 'descend' }],
  })
    .then(({ data }) => {
      setDataSource(data.data)
      setLoading(false)
    })
    .catch(() => {
      setLoading(false)
    })
}

// modal，表单提交事件
function modalSubmitClick(
  form: IAreaInsertOrUpdateForm,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  setModalVisible: Dispatch<SetStateAction<boolean>>,
  doGetTableData: () => void
) {
  setConfirmLoading(true)
  areaInsertOrUpdateApi(form)
    .then(({ data }) => {
      setModalVisible(false)
      setConfirmLoading(false)
      ToastSuccess(data.msg)
      doGetTableData() // 刷新table
    })
    .catch(() => {
      setConfirmLoading(false)
    })
}

// 删除数据
function delData(
  selectedRowKeyList: (string | number)[],
  setSelectedRowKeyList: Dispatch<SetStateAction<(string | number)[]>>,
  getTableData: () => void,
  record?: IAreaVO
) {
  doDelDataClick(
    '/area/deleteByIdSet',
    selectedRowKeyList,
    setSelectedRowKeyList,
    getTableData,
    record,
    record?.name
  )
}
